<?php


namespace app\api\model\lottery;

use app\api\model\Coupon;
use app\api\model\Order;
use app\api\model\OrderGoods;
use app\api\model\UserCoupon;
use app\common\model\Goods as GoodsModel;
use app\api\model\user\LotteryLog as UserLotteryLogModel;
use app\api\model\user\PointsLog as PointsLogModel;
use app\common\model\lottery\Action as ActionModel;
use app\api\model\lottery\Order as LotteryOrderModel;
use think\Db;

class Action extends ActionModel
{
    /**
     *  进行中的活动
     */
    public static function getGoingAction()
    {
        return self::with(['goods.logo'])->where('online', 1)->whereTime('start_time', '<=', time())->whereTime('end_time', '>', time())->select();
    }

    /**
     * 抽奖活动
     */
    public function getActionById($lottery_id)
    {
        return $this->with(['goods.logo'])->find($lottery_id);
    }

    /**
     * 点击抽奖
     */
    public  function click($lottery_id, $user)
    {
        $lottery = $this->getActionById($lottery_id);
        if (!$lottery || !$lottery->goods) {
            $this->error = "数据异常，请联系管理员";
            return false;
        }
        if ($lottery->end_time <= time()) {
            $this->error = "抽奖活动已结束，请下次参与";
            return false;
        }

        //抽奖资格
       if ($lottery->users && !in_array($user->user_id, $lottery->users)) {
           $this->error = "您暂无抽奖资格";
           return false;
       }
       //抽奖次数
        $user_lottery = UserLotteryLogModel::getUserTodayLottery($user->user_id, $lottery_id);
        if ($lottery->way == 1) {
            $count = $user_lottery ? $user_lottery->num : 0;
        } else {
            $count = UserLotteryLogModel::getUserAllLotteriesCount($user->user_id, $lottery_id);
        }
        if ($count >= $lottery->count) {
            $this->error = "您可抽奖次数已用完";
            return false;
        }
        //是否积分抽奖
        if ($lottery->integral && $user->points < $lottery->integral) {
            $this->error = "积分不足";
            return false;
        }
        //中奖奖品，全部奖品库存为0即活动结束
        $lottery_goods = $this->lotteryGoods($lottery->goods);
        if (!$lottery_goods) {
            $this->error = "抽奖活动已结束，请下次参与";
            return false;
        }

        Db::startTrans();
        try {
            //中奖记录
            Log::addLog($user->user_id, $lottery_id, $lottery_goods->id);
            //记录用户抽奖次数
            if ($user_lottery) {
                //更新
                $user_lottery->setInc('num');
            } else {
                //添加
                UserLotteryLogModel::addLog($user->user_id, $lottery_id);
            }
            //扣除库存
            $lottery_goods->setDec('num');
            //积分抽奖
            if ($lottery->integral) {
                //扣除积分
                $user->setDec('points', $lottery->integral);
                //积分明细
                PointsLogModel::addSignin($user->user_id, -$lottery->integral, '抽奖扣除积分');
            }
           //分配奖品
            self::addLotteryGoods($lottery_goods, $user);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if (isset($e)) {
            $this->error = "抽奖失败，请联系管理员";
            return false;
        }
        return $lottery_goods;
    }

    private function lotteryGoods($goods)
    {
        $arr = [];
        $data = [];
        foreach ($goods as $val) {
            $arr[$val['id']] = $val['value'] * $val['num'];
            $data[$val['id']] = $val;
        }
        if (array_sum($arr) < 1) {
            return false;
        }
        $rid = $this->get_rand($arr);
        $res = $data[$rid];
        return $res;
    }

    /*
     * 经典的概率算法
     */
    private  function get_rand($proArr) {
        $result = 0;
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /**
     * 分配奖品
     */
    private static function addLotteryGoods($lottery_goods, $user)
    {
        switch ($lottery_goods['type']) {
            //积分
            case 2:
                //增加积分
                $user->setInc('points', $lottery_goods['prize']);
                //积分明细
                PointsLogModel::addSignin($user->user_id, $lottery_goods['prize'], '中奖增加积分');
                break;
            //优惠券
            case 3:
                $coupon = Coupon::find($lottery_goods['prize']);
                UserCoupon::addUserConponLottery($user, $coupon);
                break;
            //赠品
            case 4:
                $goods_list = GoodsModel::with('image.file')->find($lottery_goods['prize']);
                //订单号
                $order_no = date('YmdHis') . mt_rand(1000, 9999);
                //订单
                $order = Order::createLotteryOrder($order_no, $user->user_id);
                //订单商品
                OrderGoods::createLotteryOrderGoods($order->order_id, $user->user_id, $goods_list);
                break;
            default:
                return true;
                break;
        }

    }
}